package com.djhu.es.core;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetSocketAddress;

public class ClientPoolFactory extends BasePoolableObjectFactory<Client> {

    private String host;
    private int port;
    private Settings settings;

    public ClientPoolFactory(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public ClientPoolFactory(String host, int port, Settings settings) {
        this.host = host;
        this.port = port;
        this.settings = settings;
    }

    @Override
    public Client makeObject() throws Exception {
        if (settings==null){
            settings = Settings.builder()
                    .put("client.transport.sniff", false).put("client.transport.ignore_cluster_name", true).build();
        }
        InetSocketTransportAddress transportAddress = new InetSocketTransportAddress(new InetSocketAddress(this.host, this.port));
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(transportAddress);
        return client;
    }

    @Override
    public boolean validateObject(Client client) {
        if (client == null){
            return false;
        }
        return true;
    }

    @Override
    public void destroyObject(Client client) throws Exception {
        client.close();
    }


}
